package com.gopi.utilities.gui;

import javax.swing.SwingUtilities;

import com.gopi.utilities.action.AbstractController;

public abstract class SwingDataHandler implements Runnable 
{
	protected Object[] workSet;
	protected Thread thread;
	protected Exception exception = null;
	protected boolean success = false;
	
	protected String action;
	protected AbstractController controller;
	
	public SwingDataHandler(Object[] workSet)
	{
		this.workSet = workSet;
	}
	
	public void startAsyncFetch(String action,AbstractController controller)
	{
		this.action = action;
		this.controller = controller;
		thread = new Thread(this);
		thread.start();
	}
	
	public void run()
	{
		try
		{
			if(action!=null && controller != null)
			{
				controller.disableCommand(action);
			}
			success = fetchData();
		}
		catch(final Exception e)
		{
			exception = e;
		}
		finally
		{
			if(action!=null && controller != null)
			{
				controller.enableCommand(action);
			}

			SwingUtilities.invokeLater(new Runnable() 
			{
				public void run()
				{
					updateData(success, exception);
				}
			});
		}
	}
	
	public abstract boolean fetchData() throws Exception;
	public abstract void updateData(boolean status,Exception e);
}
